package com.ruoyi.project.pay.ali;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ruoyi.project.pay.ali.modal.AliQueryModal;
import com.ruoyi.project.pay.common.PayUrl;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;

/**
 * @author 张泽宇
 * @date 2020/10/9 14:36
 */
public class AliQueryOrder {

    public HashMap query_order(AliQueryModal payModal) {
        HashMap<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(payModal.getOut_trade_no())) {
            map.put("status", 500);
            map.put("msg", "订单号不能为空");
            return map;
        }
        AlipayClient alipayClient = new DefaultAlipayClient(PayUrl.SERVER_URL, payModal.getAppid(),
                payModal.getPrivate_key(), PayUrl.FORMAT, PayUrl.CHARSET, payModal.getPublice_key(), PayUrl.SIGN_TYPE);
        // 封装请求支付信息
        AlipayTradeQueryRequest model = new AlipayTradeQueryRequest();
        model.setBizContent("{\"out_trade_no\":\"" + payModal.getOut_trade_no() + "\"}");

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(model);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
//        if (response.isSuccess()) {
//        Map<String, String> params = response.getBody();
        // 订单查询成功 处理业务逻辑
        if ("10000".equals(response.getCode()) && "Success".equalsIgnoreCase(response.getMsg())) {
            String trade_state = response.getTradeStatus();
            Integer state = 0;
            if ("TRADE_SUCCESS".equalsIgnoreCase(trade_state)) {
                trade_state = "交易支付成功";
                state = 200;
            } else if ("TRADE_FINISHED".equalsIgnoreCase(trade_state)) {
                trade_state = "交易结束，不可退款";
                state = 250;
            } else if ("WAIT_BUYER_PAY".equalsIgnoreCase(trade_state)) {
                trade_state = "交易创建，等待买家付款";
                state = 300;
            } else if ("TRADE_CLOSED".equalsIgnoreCase(trade_state)) {
                trade_state = "未付款交易超时关闭，或支付完成后全额退款";
                state = 350;
            }
            map.put("status", state);
            map.put("msg", trade_state);
            return map;
        }
        map.put("status", 500);
        map.put("msg", "交易不存在");
        return map;
    }
}
